﻿using System;
using System.Collections;

namespace huqiang.Communication
{
    public class DownloadRecord
    {
        BitArray record;
        public byte[] buf;
        int position = 0;
        int min;
        public int AllPart;
        public bool Compelete
        {
            get
            {
                if (buf == null)
                    return false;
                for (int i = min; i < AllPart; i++)
                    if (!record[i])
                        return false;
                return true;
            }
        }
        public void Reset(int allpart)
        {
            int c = allpart / 8;
            int r = allpart % 8;
            if (r > 0)
                c++;
            buf = new byte[c];
            record = new BitArray(buf);
            AllPart = allpart;
            min = 0;
        }
        public void Reset(int allpart,byte[] dat)
        {
            buf = dat;
            record = new BitArray(buf);
            AllPart = allpart;
            min = 0;
            for (int i = 0; i < allpart; i++)
            {
                if (!record[i])
                {
                    min = i;
                    break;
                }
            }
        }
        /// <summary>
        /// 写入分卷记录
        /// </summary>
        /// <param name="part"></param>
        /// <returns></returns>
        public bool WriteRecord(int part)
        {
            if (record == null)
                return false;
            if (record[part])
                return false;
            record[part] = true;
            for (int i = min; i < part; i++)
            {
                if (record[i] == false)
                {
                    min = i;
                    return true;
                }
            }
            min = part;
            return true;
        }
        public bool MoveNext()
        {
            if (position < AllPart)
                position++;
            else return false;
            for (int i = position; i < AllPart; i++)
            {
                if (record[i] == false)
                {
                    position = i;
                    return true;
                }
            }
            position = AllPart;
            return false;
        }
        public int Position { get => position; }
        public int GetNextPart()
        {
            for (; position < AllPart; position++)
                if (record[position] == false)
                    return position;
            return -1;
        }
        public void Begin()
        {
            position = min;
        }
    }
}
